package com.yayyay.commom.excetion;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.hutool.core.collection.CollUtil;
import com.yayyay.commom.utils.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: liangSY
 * @Date: 2021/9/23 15:07
 * @ClassName: GlobalException
 * 全局异常拦截
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {

    // 全局异常拦截（拦截项目中的所有异常）
    @ExceptionHandler(value = Exception.class)
    public ResultBean handlerException(Exception e) {
        log.error(e.getMessage(),e);
        // 不同异常返回不同状态码
        ResultBean result = null;
        if (e instanceof NotLoginException) {    // 如果是未登录异常
            NotLoginException ee = (NotLoginException) e;
            result = ResultBean.failed(ResultBean.NO_LOGIN,ee.getMessage());
        } else if (e instanceof NotRoleException) {        // 如果是角色异常
            NotRoleException ee = (NotRoleException) e;
            result = ResultBean.failed(ResultBean.FAIL,"无此角色："+ee.getRole());
        } else if (e instanceof NotPermissionException) {    // 如果是权限异常
            NotPermissionException ee = (NotPermissionException) e;
            result = ResultBean.failed(ResultBean.NO_PERMISSION,"无操作权限");
        } else {    // 普通异常, 输出：500 + 异常信息
            result = ResultBean.failed(ResultBean.FAIL,"sys error!");
        }
        // 返回给前端
        return result;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultBean handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String msg = null;
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        if (!CollUtil.isEmpty(fieldErrors)) {
            log.error(e.getMessage(), e);
            msg = fieldErrors.get(0).getDefaultMessage();
        }
        return ResultBean.failed(msg);
    }

}
